package com.smile.frame.websocket.netty.service.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.smile.frame.websocket.netty.service.repository.ClientRepository;
import com.smile.frame.websocket.netty.service.enums.CmdEnum;
import com.smile.frame.websocket.netty.service.dto.WebsocketMessageDTO;
import com.smile.frame.websocket.netty.service.util.BuilderMessageUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 客户端验证 handler
 *
 * @author LGC
 * @ChannelHandler.Sharable 保证处理器，在整个生命周期中就是以单例的形式存在
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class ClientAuthHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取请求信息
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端验证 client auth");
        // 判断消息实例
        if (!(msg instanceof TextWebSocketFrame)) {
            super.channelRead(ctx, msg);
            return;
        }
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
        WebsocketMessageDTO websocketMessageDTO = JSONUtil.toBean(textWebSocketFrame.text(), WebsocketMessageDTO.class);

        String client = ClientRepository.getClient(ctx.channel());
        String clientId = websocketMessageDTO.getClientInfo().getClientId();
        if (StrUtil.isBlank(clientId) || !client.equals(clientId)) {
            TextWebSocketFrame message = BuilderMessageUtil.buildStringMessage(websocketMessageDTO.getClientInfo(), CmdEnum.AUTH, "未认证客户端");
            ctx.writeAndFlush(message);
        } else {
            if (ctx.channel().isOpen()) {
                // 触发下一个handler
                ctx.fireChannelRead(msg);
            }
        }
    }

}
